package com.gs.cd.service.resource.controller;


import cn.hutool.core.util.StrUtil;
import com.gs.cd.api.ApiResult;
import com.gs.cd.model.resource.SysSale;
import com.gs.cd.model.resource.vo.SysSaleCopyVo;
import com.gs.cd.service.resource.service.SysResourceGroupService;
import com.gs.cd.service.resource.service.SysSaleService;
import com.seven.mybatisx.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.io.Serializable;

/**
 * 销售单元模块
 *
 * @author seven
 * @since 2020-12-22
 */
@RestController
@RequestMapping("/resource/sysSale")
public class SysSaleController extends AbstractController<SysSale, SysSaleService> {

    @Autowired
    private SysResourceGroupService sysResourceGroupService;

    /**
     * 删除 并删除相关资源组
     *
     * @param id
     * @return
     */
    @DeleteMapping("deleteRe/{id}")
    public ApiResult deleteReById(@PathVariable String id) {
        if (!checkSaleById(id)) return ApiResult.error("无效id,无法操作");
        return iService.removeSaleAndRelationsById(id) ?
                ApiResult.success() : ApiResult.error();
    }

    /**
     * 导出sql
     */
    @GetMapping("export/sql/{id}")
    public ApiResult exportSql(@PathVariable String id) {
        if (!checkSaleById(id)) return ApiResult.error("无效id,无法操作");
        return ApiResult.success();
    }


    /**
     * 新建 & 复用
     */
    @PostMapping("saveAndCopy")
    public ApiResult saveAndCopy(@RequestBody SysSaleCopyVo sysSaleCopyVo) {
        if (checkSaleByCode(sysSaleCopyVo.getCode()))
            return ApiResult.error(String.format("code'%s'已经存在了", sysSaleCopyVo.getCode()));
        if (!StrUtil.isEmpty(sysSaleCopyVo.getSourceSaleCode())) {
            //1. 复制资源组
            sysResourceGroupService.copy(sysSaleCopyVo.getSourceSaleCode(), sysSaleCopyVo.getCode());
            //todo 2. 复制默认角色
        }
        return saveOrUpdate(sysSaleCopyVo);
    }

    private boolean checkSaleById(String id) {
        SysSale byId = iService.getById(id);
        //true表示存在
        return byId != null;
    }

    private boolean checkSaleByCode(String code) {
        SysSale byCode = iService.getByCode(code);
        //true表示存在
        return byCode != null;
    }

}

